import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:group_list_view/group_list_view.dart';
import 'package:loading_animation_widget/loading_animation_widget.dart';
import 'package:share_fit/app/components/back_btn_icon.dart';
import 'package:share_fit/app/helper/ext/tr_ext.dart';
import 'package:share_fit/app/models/device/contact_model.dart';
import 'package:share_fit/app/tools/color_const.dart';
import 'package:share_fit/generated/locales.g.dart';
import 'package:alphabet_list_view/alphabet_list_view.dart';
import 'package:simple_circular_progress_bar/simple_circular_progress_bar.dart';
import 'package:sprintf/sprintf.dart';

import 'import_contacts_logic.dart';

class ImportContactsPage extends StatelessWidget {
  ImportContactsPage({super.key});

  final logic = Get.find<ImportContactsLogic>();
  final state = Get
      .find<ImportContactsLogic>()
      .state;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          leading: BackBtnIcon(onTap: () => {Get.back()}),
          centerTitle: true,
          title: GetBuilder<ImportContactsLogic>(
            id: "title_item",
              builder: (logic) {
            return Text(state.checkList.isEmpty ? LocaleKeys.settings_contacts.ts : sprintf(LocaleKeys.contact_selected.ts, [state.checkList.length, state.totalCount]),
                style: TextStyle(fontSize: 54.sp));
          }),
        ),
        bottomSheet: _buildBottomSheet(),
        body: Stack(
          children: [
            Column(
              children: [
                Expanded(child: _buildBody(context)),
                SizedBox(height: 60.h),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(LocaleKeys.contact_title_all.ts,
                        style: TextStyle(fontSize: 42.sp)),
                    SizedBox(width: 20.w),
                    GetBuilder<ImportContactsLogic>(
                      id: "total_item",
                      init: logic,
                      builder: (ImportContactsLogic controller) {
                        return Text('${state.totalCount}',
                            style: TextStyle(fontSize: 54.sp));
                      },
                    ),
                  ],
                ),
                SizedBox(height: 340.h),
              ],
            ),
          ],
        ));
  }

  _buildBody2(BuildContext context) {
    return Padding(
      padding: EdgeInsets.only(left: 43.w, right: 3.w, top: 10.h),
      child: GetBuilder<ImportContactsLogic>(
          id: "list_view",
          builder: (logic) {
            final List<AlphabetListViewItemGroup> items = [];

            for (var contactModel in state.contactList) {
              items.add(AlphabetListViewItemGroup(
                tag: contactModel.section,
                children: contactModel.contacts
                    .map((e) => _buildListWidget(context, e)),
              ));
            }

            return AlphabetListView(
              items: items,
              options: AlphabetListViewOptions(
                listOptions: ListOptions(
                  listHeaderBuilder: (context, symbol) =>
                      SizedBox(
                        height: 120.h,
                        child: Padding(
                          padding: EdgeInsets.symmetric(vertical: 30.h),
                          child: Text(
                            symbol,
                            style: TextStyle(
                                fontSize: 42.sp, color: const Color(
                                0xff434343)),
                          ),
                        ),
                      ),
                ),
                // scrollbarOptions: const ScrollbarOptions(
                //   backgroundColor: Colors.yellow,
                // ),
                overlayOptions: const OverlayOptions(
                  showOverlay: false,
                ),
              ),
            );
          }),
    );
  }

  _buildBody(BuildContext context) {
    return Padding(
      padding: EdgeInsets.only(left: 43.w, right: 43.w, top: 10.h),
      child: GetBuilder<ImportContactsLogic>(
          id: "list_view",
          builder: (logic) {
            return GroupListView(
              sectionsCount: state.contactList.length,
              countOfItemInSection: (int section) {
                return state.contactList[section].contacts.length;
              },
              itemBuilder: (BuildContext context, IndexPath index) {
                return _buildListWidget(context,
                    state.contactList[index.section].contacts[index.index]);
              },
              groupHeaderBuilder: (BuildContext context, int section) {
                return SizedBox(
                  height: 120.h,
                  child: Padding(
                    padding: EdgeInsets.symmetric(vertical: 30.h),
                    child: Text(
                      state.contactList[section].section,
                      style: TextStyle(
                          fontSize: 42.sp, color: const Color(0xff434343)),
                    ),
                  ),
                );
              },
              separatorBuilder: (context, index) => SizedBox(height: 40.h),
              sectionSeparatorBuilder: (context, section) =>
                  SizedBox(height: 10.h),
            );
          }),
    );
  }

  _buildListWidget(BuildContext context, contactItem) {
    return Column(
      children: [
        Container(
          padding: EdgeInsets.only(left: 60.w, right: 10.w),
          decoration: BoxDecoration(
            color: Colors.white70.withOpacity(0.9),
            borderRadius: BorderRadius.circular(60.r),
          ),
          height: 175.h,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    constraints: BoxConstraints(
                      maxWidth: 700.w,
                    ),
                    child: Text(
                      contactItem.name,
                      maxLines: 1,
                      style: TextStyle(
                          fontSize: 48.sp, color: const Color(0xff434343)),
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                  Text(
                    contactItem.phone,
                    style:
                    TextStyle(fontSize: 36.sp, color: const Color(0xff434343)),
                  ),
                ],
              ),
              _showCheckBox(contactItem),
            ],
          ),
        ),
        // SizedBox(height: 40.h,)
      ],
    );
  }

  _buildBottomSheet() {
    return Container(
      height: 297.h,
      decoration: BoxDecoration(
        color: Colors.white70.withOpacity(0.9),
        borderRadius: BorderRadius.only(
            topLeft: Radius.circular(60.r), topRight: Radius.circular(60.r)),
      ),
      padding: EdgeInsets.symmetric(horizontal: 206.w),
      child: GetBuilder<ImportContactsLogic>(
        id: "bottom_sheet",
        init: logic,
        builder: (ImportContactsLogic controller) {
          return Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: _getActionButtons(),
          );
        },
      ),
    );
  }

  _getActionButtons() {
    return [_getImportBtn(), _getCheckAllWidget()];
  }

  Widget _getImportBtn() {
    return GestureDetector(
      onTap: () => _doImport(),
      child: Row(
        children: [
          Image.asset('assets/images/device/ic_contacts_import.png',
              height: 66.h, width: 66.w),
          SizedBox(width: 20.w),
          Text(LocaleKeys.import.ts, style: TextStyle(fontSize: 48.sp)),
        ],
      ),
    );
  }

  Widget _getCheckAllWidget() {
    return Row(
      children: [
        Checkbox(
          activeColor: Colors.red,
          value: state.isSelectAll,
          onChanged: (value) => logic.onSelectAll(value),
          shape: const CircleBorder(),
        ),
        Text(LocaleKeys.select_all.ts, style: TextStyle(fontSize: 48.sp))
      ],
    );
  }

  Widget _showCheckBox(ContactItem contact) {
    return Checkbox(
      activeColor: Colors.red,
      value: contact.imported,
      onChanged: (value) => logic.onContactCheck(contact, value),
      shape: const CircleBorder(),
    );
  }

  void _doImport() {
    if (state.checkList.isNotEmpty) {
      showContactsSyncDialog();
    }
    logic.doImportContact();
  }

  void showContactsSyncDialog() {
    if (Get.overlayContext != null) {
      showDialog(
          context: Get.overlayContext!,
          barrierDismissible: Platform.isIOS,
          builder: (BuildContext context) {
            return Material(
              type: MaterialType.transparency,
              child: Center(
                child: SizedBox(
                  width: 916.w,
                  height: 736.w,
                  child: Container(
                    decoration: const ShapeDecoration(
                      color: Color(0xffffffff),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.all(
                          Radius.circular(20.0),
                        ),
                      ),
                    ),
                    child: GetBuilder<ImportContactsLogic>(
                      id: "dialog_item",
                      init: logic,
                      builder: (ImportContactsLogic logic) {
                        if (logic.state.isSyncing.value) {
                          logic.state.progressNotifier?.value =
                              logic.state.syncProgress.value.toDouble();
                          return Platform.isAndroid ? SimpleCircularProgressBar(
                            size: 120,
                            maxValue: logic.state.checkList.length.toDouble(),
                            valueNotifier: logic.state.progressNotifier,
                            progressColors: [
                              ColorConst.accentColor,
                              ColorConst.activeColor
                            ],
                            fullProgressColor: const Color(0xff00d687),
                            backColor: ColorConst.secondaryFontColor,
                            mergeMode: true,
                            onGetText: (double value) {
                              TextStyle centerTextStyle = TextStyle(
                                fontSize: 30,
                                fontWeight: FontWeight.bold,
                                color: ColorConst.accentColor,
                              );

                              return Text(
                                '${value.toInt()}',
                                style: centerTextStyle,
                              );
                            },
                          ) : Container(
                            alignment: Alignment.center,
                            child: SizedBox(
                              height: 100.h,
                              width: 200.w,
                              child: LoadingAnimationWidget.staggeredDotsWave(
                                color: const Color(0xffff6630),
                                size: 50,
                              ),
                            ),
                          );
                        } else {
                          return Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              SizedBox(height: 30.h),
                              Image.asset(
                                  'assets/images/device/device_dialog_success.png',
                                  width: 222.w,
                                  height: 222.h),
                              SizedBox(height: 30.h),
                              Text(LocaleKeys.contact_sync_success.ts,
                                  style: TextStyle(fontSize: 54.sp)),
                              SizedBox(height: 50.h),
                            ],
                          );
                        }
                      },
                    ),
                  ),
                ),
              ),
            );
          });
    }
  }
}
